"""
职位数据API视图
"""
from rest_framework import viewsets, filters
from rest_framework.decorators import action
from django_filters.rest_framework import DjangoFilterBackend
from django.db.models import Q

from .models import Position, AIPosition
from .serializers import (
    PositionSerializer, PositionListSerializer,
    AIPositionSerializer, AIPositionListSerializer
)
from utils.response import success_response, error_response


class PositionViewSet(viewsets.ReadOnlyModelViewSet):
    """
    职位信息ViewSet
    
    提供职位列表、详情、搜索和筛选功能
    """
    queryset = Position.objects.all()
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['category', 'big_category', 'city', 'company_size', 'finance_stage', 'education', 'work_year']
    search_fields = ['position_name', 'company_full_name', 'position_detail']
    ordering_fields = ['salary_avg', 'create_time', 'imported_at']
    ordering = ['-imported_at']
    
    def get_serializer_class(self):
        if self.action == 'list':
            return PositionListSerializer
        return PositionSerializer
    
    def list(self, request, *args, **kwargs):
        """职位列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return success_response(data=serializer.data, message='获取职位列表成功')
    
    def retrieve(self, request, *args, **kwargs):
        """职位详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message='获取职位详情成功')
    
    @action(detail=False, methods=['get'])
    def filter_options(self, request):
        """
        获取筛选器选项
        
        返回所有可用的筛选选项，用于前端构建筛选器
        """
        options = {
            'cities': list(Position.objects.exclude(city__isnull=True).values_list('city', flat=True).distinct().order_by('city')),
            'categories': list(Position.objects.exclude(category__isnull=True).values_list('category', flat=True).distinct().order_by('category')),
            'big_categories': list(Position.objects.exclude(big_category__isnull=True).values_list('big_category', flat=True).distinct().order_by('big_category')),
            'company_sizes': list(Position.objects.exclude(company_size__isnull=True).values_list('company_size', flat=True).distinct()),
            'finance_stages': list(Position.objects.exclude(finance_stage__isnull=True).values_list('finance_stage', flat=True).distinct()),
            'work_years': list(Position.objects.exclude(work_year__isnull=True).values_list('work_year', flat=True).distinct()),
            'educations': list(Position.objects.exclude(education__isnull=True).values_list('education', flat=True).distinct()),
        }
        
        return success_response(data=options, message='获取筛选选项成功')


class AIPositionViewSet(viewsets.ReadOnlyModelViewSet):
    """
    AI岗位信息ViewSet
    
    提供AI相关岗位的列表、详情、搜索和筛选功能
    """
    queryset = AIPosition.objects.all()
    filter_backends = [DjangoFilterBackend, filters.SearchFilter, filters.OrderingFilter]
    filterset_fields = ['location_city', 'company_scale', 'education', 'experience']
    search_fields = ['position_name', 'company_name', 'tags']
    ordering_fields = ['salary_avg', 'imported_at']
    ordering = ['-imported_at']
    
    def get_serializer_class(self):
        if self.action == 'list':
            return AIPositionListSerializer
        return AIPositionSerializer
    
    def list(self, request, *args, **kwargs):
        """AI岗位列表"""
        queryset = self.filter_queryset(self.get_queryset())
        page = self.paginate_queryset(queryset)
        
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        
        serializer = self.get_serializer(queryset, many=True)
        return success_response(data=serializer.data, message='获取AI岗位列表成功')
    
    def retrieve(self, request, *args, **kwargs):
        """AI岗位详情"""
        instance = self.get_object()
        serializer = self.get_serializer(instance)
        return success_response(data=serializer.data, message='获取AI岗位详情成功')

